package com.ljy.springcloud.my.impl;

import com.ljy.springcloud.my.MyLoadBalanced;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLoadBalancedImpl implements MyLoadBalanced {
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Override
    public ServiceInstance getServiceInstance(List<ServiceInstance> serviceInstanceList) {
        // 返回一台服务器
        int index = getAndAdd() % serviceInstanceList.size();
        return serviceInstanceList.get(index);
    }

    public final int getAndAdd() {
        int curr;
        int next;
        do {
            curr = atomicInteger.get();
            //System.out.println("curr:"+curr);
            next = curr >= Integer.MAX_VALUE ? 0 : curr + 1;
        } while (!atomicInteger.compareAndSet(curr, next));//一定要取反，否则会循环很久
        System.out.println("next:" + next);
        return next;
    }

}
